#include "editer_bar.h"
#include "ui_editer_bar.h"

editer_bar::editer_bar(QFrame* i_text_area, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::editer_bar),
    text_area(i_text_area)
{
    ui->setupUi(this);
    all_width = 0;
    GlobalSignalMgr::get_instance()->attach(SignalType::SIG_FILE_ADD_EDIT_STRING, this, SLOT(add_file(QString)));
    GlobalSignalMgr::get_instance()->attach(SignalType::SIG_FILE_SAVE_SINGLE_VOID,this, SLOT(Save_Signal_file()));
    GlobalSignalMgr::get_instance()->attach(SignalType::SIG_FILE_SAVE_ALL_VOID,this, SLOT(Save_All_file()));
    GlobalSignalMgr::get_instance()->attach(SignalType::SIG_FILE_CLOSE_ONE_VOID,this, SLOT(CloseOneFile()));
    GlobalSignalMgr::get_instance()->attach(SignalType::SIG_FILE_NAME_CHANGED_STRING, this, SLOT(OnFileRenamed(QString)));
    resize(parent->width(), parent->height());
    timer_flush_status =  startTimer(1000);
}

editer_bar::~editer_bar()
{
    delete ui;
}

const QString &editer_bar::get_current_file()
{
    return editer_bar::Current_file;
}

void editer_bar::add_file(QString full_file_path)
{
    QList<edit_struct*>::iterator iter = pb_list.begin();
    bool has_button = false;
    while (iter != pb_list.end()){
        if (!(*iter)->pb->getValue().compare(full_file_path)){
            has_button = true;
        }
        ++iter;
    }
    if (!has_button){
        //增加tab栏按钮
        MButton* pb = new MButton();
        pb->setParent(this);
        pb->setValue(full_file_path);
        int bt_wd = getTextSize(pb->get_limit_val()).width();
        pb->move(all_width,0);
        all_width+= bt_wd;
        pb->resize(bt_wd,this->height());
        pb->setValue(full_file_path);
        connect(pb, SIGNAL(MClicked(QString)), this, SLOT(MButton_clicked(QString)));
        connect(pb, SIGNAL(MDoubleClicked(QString)), this, SLOT(MButton_DoubleClicked(QString)));
        pb->show();
        //增加文本框
        QString lower_file_name = full_file_path.toLower();
        EditBaseWidget* text_obj;
        if(lower_file_name.endsWith(".md") || lower_file_name.endsWith(".markdown") ){
            text_obj = new markdown_editer(full_file_path, text_area);
        }
        else if (lower_file_name.endsWith(".md2")){
            text_obj = new markdown_editer2(full_file_path, text_area);
        }
        else{
            text_obj = new EditBaseWidget(full_file_path, text_area);
        }
        text_obj->load_window();
        text_obj->show();
        //增加到排序列表
        edit_struct* es = new edit_struct;
        es->editer = text_obj;
        es->pb = pb;
        pb_list.append(es);
        //调整页面大小
        MResize_event(width(), height());
    }
    editer_bar::Current_file = full_file_path;
    update_button_status();
}

void editer_bar::MButton_clicked(QString file_path)
{
    add_file(file_path);
}

void editer_bar::MButton_DoubleClicked(QString file_path)
{
    CloseOneFile(file_path);
}

void editer_bar::CloseOneFile(QString file_path)
{
    /*
    1. 关闭输入的文件
    2. 如果关闭的文件前有则显示
    3. 如果关闭的文件前没有则显示下一个
    */

    int show_index = -1;
    int close_index = -1;
    edit_struct* close_node = nullptr;
    int all_size = pb_list.length();
    all_width = 0;
    //1. 找到需要关闭的文件index,并调整未关闭按钮位置
    for (int i = 0; i < all_size; ++i){
        edit_struct* node = (edit_struct*) pb_list.at(i);
        QString file_name = node->pb->getValue();
        if (!file_name.compare(file_path)){
            close_node = node;
            close_index = i;
        }
        else{
            node->pb->move(all_width, 0);
            all_width += node->pb->width();
        }
    }
    //2. 关闭该页面
    if(close_node){
        if(makesure_savefile_onclose(close_node)){
            close_node->editer->hide();
            close_node->editer->close();
            close_node->pb->hide();
            close_node->pb->close();
            pb_list.removeOne(close_node);
        }
        else{
            return;
        }
    }
    //3. 找出要显示的页面
    if (all_size == 0 || (all_size == 1 && close_index != -1)){
        show_index = -1;
    }
    else if (close_index - 1 >= 0 ){
        show_index = close_index -1;
    }
    else{
        show_index = close_index;
    }
    //4. 重新遍历隐藏非活动editer
    editer_bar::Current_file = "";
    for(int i =0; i< pb_list.length();++i){
        edit_struct* node = (edit_struct*) pb_list.at(i);
        if(i == show_index){
            editer_bar::Current_file = node->pb->getValue();
            node->editer->show();
        }
        else{
            node->editer->hide();
        }
    }
    update_button_status();
}

void editer_bar::CloseOneFile()
{

    CloseOneFile(editer_bar::Current_file);
}

void editer_bar::CloseAllFile()
{

}

void editer_bar::OnFileRenamed(QString replace_str)
{
    QString old_full_file_path = get_old_path_from_replace_str(replace_str);
    QList<edit_struct*>::iterator iter = pb_list.begin();
    if(!old_full_file_path.compare(editer_bar::Current_file)){
        editer_bar::Current_file = get_new_file_name_from_replace_str(replace_str);
    }
    while (iter != pb_list.end()){
        if(!(*iter)->pb->getValue().compare(old_full_file_path)){
            QString new_full_file_path = get_new_file_name_from_replace_str(replace_str);
            QString new_file_name = get_file_name_use_path(new_full_file_path);
            (*iter)->pb->setText(new_file_name);
            (*iter)->pb->setValue(new_full_file_path);
            (*iter)->editer->update_file_info(new_full_file_path);
        }
        ++iter;
    }

}

void editer_bar::MResize_event(int w, int h)
{
    QList<edit_struct*>::iterator iter = pb_list.begin();
    resize(w, h);
    while (iter != pb_list.end()){
        (*iter)->pb->resize((*iter)->pb->width(), h);
        (*iter)->editer->resize_editer(text_area->width(), text_area->height());
        ++iter;
    }
}



void editer_bar::Save_Signal_file()
{
    QList<edit_struct*>::iterator iter = pb_list.begin();
    while (iter != pb_list.end()){
        if ((*iter)->pb->getButton_status() == BUTTON_STATUS_FILE_CHANGED &&
                (*iter)->editer->is_file_changed()
                ){
            (*iter)->editer->save_file();
        }
        ++iter;
    }

}

void editer_bar::Save_All_file()
{
    QList<edit_struct*>::iterator iter = pb_list.begin();
    while (iter != pb_list.end()){
        if ((*iter)->pb->getButton_status() == BUTTON_STATUS_FILE_CHANGED){
            (*iter)->editer->save_file();
        }
        ++iter;
    }
    update_button_status();
}

QSize editer_bar::getTextSize(const QString &text) const
{
    QFont font;
    font.setPixelSize(16);
    QFontMetrics metrics(font);
    return metrics.boundingRect(text).size();
}

void editer_bar::update_button_status()
{
    QList<edit_struct*>::iterator iter = pb_list.begin();
    while (iter != pb_list.end()){
        if(!(*iter)->pb->getValue().compare(editer_bar::Current_file)){
            (*iter)->pb->setButtonFile_status(BUTTON_STATUS_FILE_CURRENT_SHOW);
            (*iter)->editer->show();
        }
        else{
            (*iter)->pb->setButtonFile_status(BUTTON_STATUS_FILE_CURRENT_NOTSHOW);
            (*iter)->editer->hide();
        }
        if((*iter)->editer->is_file_changed()){
            (*iter)->pb->setButtonFile_status(BUTTON_STATUS_FILE_CHANGED);
        }
        else{
            (*iter)->pb->setButtonFile_status(BUTTON_STATUS_FILE_NO_CHANGED);
        }
        ++iter;
    }
}

void editer_bar::timerEvent(QTimerEvent *e)
{
    update_button_status();
}

bool editer_bar::makesure_savefile_onclose(edit_struct * editer_st)
{
    if(!editer_st->editer->is_file_changed()){
        return true;
    }
    QMessageBox box(QMessageBox::NoIcon,"文件未保存","是否保存文件",QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel);
    int result = box.exec();
    switch(result){
    case QMessageBox::Yes:
        editer_st->editer->save_file();
        return true;
        break;
    case QMessageBox::No:
        return true;
        break;
    case QMessageBox::Cancel:
        return false;
        break;
    }

}
